<template>
  <div class="app-container">
    <div ref="gantt" class="left-container">
    </div>
    <gan-te-tu-modal ref="ganTeTuModal" @ok="modalOk()"></gan-te-tu-modal>
    <a-menu :style="menuStyle" v-if="menuVisible">
      <a-menu-item @click="updateTask('修改')">编辑</a-menu-item>
      <a-menu-item @click="deleteItem(3)">
        <a-popconfirm title="确定删除吗?" @confirm="() => deleteMouldItem()">
          <a>删除</a>
        </a-popconfirm>
      </a-menu-item>
    </a-menu>
  </div>
</template>

<script>

  import gantt from 'dhtmlx-gantt'  // 引入模块
  import ganTeTuModal from "./ganTeTuModal";
  import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
  import {getAction,putAction,postAction,deleteAction} from "../../../../../api/manage";
  import {filterDictTextByCache} from '@comp/dict/JDictSelectUtil'

  export default {
    name: "constructionDetail",
    components:{
      ganTeTuModal
    },
    props: {
      mouldId: 0
    },
    data() {
      return {
        tasks: {
          data: [],
          links: []
        },
        clickItem:0,
        url: {
          list: "/ghConstructionMouldItem/list",
          add: "/ghConstructionMouldItem/add",
          edit: "/ghConstructionMouldItem/edit",
          delete: "/ghConstructionMouldItem/delete"
        },
        menuVisible: false,
        menuStyle: {
          position: "absolute",
          top: "0",
          left: "0",
          border: "1px solid #eee"
        },
        currentTask:{},
      }
    },
    created() {
      //清空gantt数据
      gantt.clearAll();
      this.getProjectTaskData();
      let _this=this;
      window.modify=_this.modify;
      window.addTask=_this.addTask;
    },
    methods: {
      modalOk(){
        this.getProjectTaskData();
      },
      deleteMouldItem(){
        deleteAction(this.url.delete, {id: this.currentTask.id}).then((res) => {
          if (res.success) {
            //清空gantt数据
            gantt.clearAll();
            this.getProjectTaskData();
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      deleteItem(value){
        this.clickItem = value;
      },
      showMenu(record,event){
        this.currentTask = record;
        if (record != null){
          this.menuVisible = true;
          this.menuStyle.top = event.clientY - 75 + "px";
          this.menuStyle.left = event.clientX - 25 + "px";
          document.body.addEventListener("click", this.bodyClick);
        }
      },
      //左键点击其他地方关闭菜单
      bodyClick() {
        if (this.clickItem != 3){
          this.menuVisible = false;
          document.body.removeEventListener("click", this.bodyClick);
        }else {
          this.clickItem = 0;
        }
      },
      //获取甘特图数据
      getProjectTaskData() {
        this.tasks.data = [];
        getAction(this.url.list,{id: this.mouldId}).then((res) => {
          if (res.success) {
            //this.tasks.data = res.result.records || res.result;
            for (let i = 0; i < res.result.length; i++) {
              var item1 = res.result[i];
              item1.start_date = res.result[i].startWorkTime;
              item1.open = true;
              item1.duration = res.result[i].workTimeLimit;
              item1.text = res.result[i].itemName;
              /*item1.toolTipsTxt = res.result[i].itemName;*/
              //设置类型
              item1.type = res.result[i].id;
              this.tasks.data.push(item1)
              for (let j = 0; j < res.result[i].children.length; j++) {
                var item = res.result[i].children[j];
                item.start_date = res.result[i].children[j].startWorkTime;
                item.duration = res.result[i].children[j].workTimeLimit;
                item.text = res.result[i].children[j].itemName;
                item.parent = res.result[i].id;
                //item.toolTipsTxt = res.result[i].children[j].itemName;
                this.tasks.data.push(item)
              }
            }
            /*this.tasks.data.map(function (current,ind,arry) {
              var newObj = {};
              if (current.type){
                if (current.type == 1){
                  newObj = Object.assign({},current,{'color':'#fcca02'})
                }else if(current.type == 2){
                  newObj = Object.assign({},current,{'color':'#fec0dc'})
                }else if(current.type == 3){
                  newObj = Object.assign({},current,{'color':'#62ddd4'})
                }
              }
              return newObj;
            })*/
            // 数据解析:将数据解析到gantt列数据中
            gantt.parse(this.tasks);
            // 刷新数据
            gantt.refreshData();
          }
        })
      },
      //修改数据：拖动任务，拖动任务进度
      updateData(record) {
        var that = this;
        let params = {};
        params.id = record.id;
        params.startWorkTime = this.formatDateTime(record.start_date);
        params.workTimeLimit = record.duration;
        putAction(this.url.edit, params).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            //that.$emit('ok');
            that.getProjectTaskData();
          } else {
            that.$message.warning(res.message);
          }
        })
      },
      formatDateTime(inputTime) {
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        var d = date.getDate();
        d = d < 10 ? "0" + d : d;
        var h = date.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? "0" + minute : minute;
        second = second < 10 ? "0" + second : second;
        return y + "-" + m + "-" + d;
      },
      updateTask(title){
        var $this = this;
        $this.$refs.ganTeTuModal.title = title;
        $this.$refs.ganTeTuModal.edit($this.currentTask);
      },
      //自定义新增任务
      addTask(title,id) {
        var $this = this;
        $this.$refs.ganTeTuModal.title = title;
        $this.$refs.ganTeTuModal.add(id,this.mouldId);
        //删除任务：每次调用gantt内置新增事件时，gantt会直接新增任务到甘特图中，而我们需要的是自定义新增任务
        //gantt.deleteTask(taskId);
        //灯箱事件必须返回布尔值，这里使用了自定义灯箱返回false，即不打开灯箱
        return false;
      }
    },
    mounted() {
      var $this = this;
      //本地化
      gantt.i18n.setLocale('cn');
      //灯箱事件
      gantt.attachEvent('onBeforeLightbox', function (task_id) {
        //刷新灯箱数据
        //gantt.resetLightbox();
        //true：打开灯箱
        //return true;
        //这里调用了自己的页面，没有打开默认灯箱
        //$this.addTask("修改",task_id);
      });
      gantt.attachEvent("onAfterTaskDrag", function (id, mode, e) {
        var globalTaskIndex = gantt.getGlobalTaskIndex(id); // -> 10
        $this.updateData(gantt.getTaskByIndex(globalTaskIndex))
      });
      //任务的日期（格式化）
      /*gantt.templates.task_date= function(date){
        return gantt.date.date_to_str(gantt.config.task_date)(date);
      };*/
      gantt.attachEvent("onContextMenu", function (id, mode, e) {
        var globalTaskIndex = gantt.getGlobalTaskIndex(id); // -> 10
        var record = gantt.getTaskByIndex(globalTaskIndex);
        $this.showMenu(record,e);
      });


      /*gantt.attachEvent("onTaskDblClick", function (id, mode, e) {
        alert(123)
      });*/

      /*gantt.attachEvent("onTaskRowClick", function (id, mode, e) {
        alert(123)
      });*/

      //只读模式：打开后不可以操作甘特图
      gantt.config.readonly = false;
      //是否显示左侧树表格
      gantt.config.show_grid = true;
      //gantt内置异常消息处理，建议关闭，如果不关闭，会弹出异常信息，异常信息必须鼠标点击才会消失。
      gantt.config.show_errors = false;
      //表头高度
      gantt.config.scale_height = 50;

      //设置x轴日期
      gantt.config.scale_unit = "day";
      gantt.config.step = 1;
      gantt.config.date_scale = "星期" + "%D"
      //在时间线上增加一行显示日期
      gantt.config.subscales = [
        {unit: 'day', step: 1, date: '%M' + '%d' + '日'}
      ]
      //从后端过来的数据格式化
      gantt.config.xml_date = '%Y-%m-%d'
      //自适应甘特图的尺寸大小
      gantt.config.autosize = true;

      gantt.config.details_on_create = true;

      //禁止拖动任务
      gantt.config.drag_move = true;
      //禁止拖动任务进度
      gantt.config.drag_progress = true;
      //禁止拖放添加Link
      //gantt.config.drag_links = true;
      //以下代码可实现移动，具体保存自己实现（有移动后的方法onAfterTaskMove）
      //gantt.config.order_branch = true;
      //gantt.config.order_branch_free = true;
      //开启标记
      gantt.plugins({
        marker: true
      });
      //标记当前日期
      var dateToStr = gantt.date.date_to_str(gantt.config.task_date);
      var markerId = gantt.addMarker({
        start_date: new Date(),
        css: 'today',	//标记样式，style中对应
        text: 'Today',
        title: dateToStr(new Date())
      });
      gantt.getMarker(markerId);
      var colHeader = '<div class="gantt_grid_head_cell gantt_grid_head_add" onclick="addTask('+"'添加'"+',1)"></div>'
      gantt.config.columns = [
        {
          name: 'itemName',
          label: '任务名称',
          tree: true,
          width: '160',
        },
        {
          name: 'startWorkTime',
          label: '开工时间',
          width: '80',
          align: "center"
        },
        {
          name: 'workTimeLimit',
          label: '工期',
          width: '40',
          align: "center"
        },
        {
          name: 'personInCharge',
          label: '负责人',
          align: 'center',
          width: '80',
          template: function(task){
            return filterDictTextByCache('construction_mould_item_person_in_charge', task.personInCharge);
          },
        },
        {
          name: "", label: colHeader, width: 100,
          template: function (task) {
            return '<div class="gantt_grid_head_add" onclick="addTask('+"'添加'"+',' + task.id + ')"></div>';
          }
        }
      ];
      // 初始化
      gantt.init(this.$refs.gantt)
    }
  }
</script>

<style scoped>
  /*.left-container {
    height: 2000px;
  }*/

  .app-container{
    /*height: 1500px;*/
  }

  .fa {
    cursor: pointer;
    font-size: 14px;
    text-align: center;
    padding: 5px;
  }

  .fa：hover {
    opacity: 1;
  }

  .fa-pencil {
    color: #ffa011;
  }

  .fa-plus {
    color: #328EA0;
  }

  .fa-times {
    color: red;
  }
</style>